package com.malware.detection;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Set;


import android.util.Log;



public class CpuUsage {
	StringBuilder TAG = new StringBuilder("PoornimaMalware");

	//filter the apps from input list that are in top 10 cpu usage in the system
	public Hashtable<String,Integer> findSuspiciousApps(Set<String> appsWithRecordingPermission)
	{
		Hashtable<String,Integer> suspectApps = new Hashtable<String,Integer>();
		ArrayList<String> cpuUsageList=getUsage();
		for(String line:cpuUsageList)
		{	
			for(String packageName:appsWithRecordingPermission)
				if(line.contains(packageName))
				{
					int indexPer=line.indexOf("%");
					int percentage=Integer.parseInt(line.substring(indexPer-2,indexPer).trim());
					suspectApps.put(packageName, percentage);
					//Log.d("SUSPO", packageName+"   "+persentage);
				}	
		}
		
		Log.d(TAG.toString(), "CpuUsage: suspicious apps:" + suspectApps.toString());
		return suspectApps;
	}
	
	
	
	//reference :http://www.cleanappnetwork.com/tutorial-finding-cpu-usage-for-individual-android-apps/
	private ArrayList<String> getUsage() {
		ArrayList<String> list = new ArrayList<String>();
		try {
			// -m 10, how many entries you want, -d 1, delay by how much, -n 1,
			// number of iterations
			Process p = Runtime.getRuntime().exec("top -m 10 -d 1 -n 1");

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			int i = 0;
			String line = reader.readLine();
			while (line != null) {
				list.add(line);
				line = reader.readLine();
				i++;
			}
			p.waitFor();
			return list;
			
		} catch (Exception e) {
			e.printStackTrace();
			Log.d("malware",  "Catch");
			return null;
		}

	}
}
